package com.ds.esd.localproxy.handler.dsm;

import com.ds.common.JDSException;
import com.ds.common.md5.MD5;
import com.ds.common.util.StringUtility;
import com.ds.config.JDSUtil;
import com.ds.esd.client.ESDFacrory;
import com.ds.esd.custom.CustomViewFactory;
import com.ds.esd.custom.bean.MethodConfig;
import com.ds.esd.localproxy.handler.AbstractRADHandler;
import com.ds.esd.project.ProjectCacheManager;
import com.ds.server.httpproxy.core.Handler;
import com.ds.server.httpproxy.core.HttpRequest;
import com.ds.server.httpproxy.core.HttpResponse;
import com.ds.server.httpproxy.core.Server;
import com.ds.vfs.FileInfo;
import com.ds.vfs.ct.CtVfsService;
import com.ds.vfs.ct.admin.CtAdminVfsServiceImpl;
import com.ds.web.RequestMethodBean;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
import java.util.regex.Pattern;


public class DSMClsHandler extends AbstractRADHandler implements Handler {
    private static final Logger log = Logger.getLogger(com.ds.server.httpproxy.handler.ResourceHandler.class.getName());
    private String resourceMount;
    CtAdminVfsServiceImpl vfsClient;
    Pattern rule;

    public boolean initialize(String handlerName, Server server) {
        super.initialize(handlerName, server);
        this.resourceMount = RESOURCE_MOUNT_OPTION.getProperty(server, handlerName);
        rule = Pattern.compile(RULE_OPTION.getProperty(server, handlerName));
        return true;
    }


    protected boolean handleBody(HttpRequest request, HttpResponse response) throws IOException {
        String path = request.getPath();
        boolean ruleMatches = rule.matcher(path).matches();
        if (!ruleMatches) {
            return false;
        }

        String projectName = this.getProjectName(request);
        boolean projectMatches = false;
        if (projectName != null) {
            Pattern projectRule = Pattern.compile(".*/(" + projectName + ")?.*");
            projectMatches = projectRule.matcher(path).matches();
        }
        if (!projectMatches) {
            return false;
        }


        path = this.formatPath(request.getUrl(), projectName);
        String mimeType = getMimeType(path);
        path = StringUtility.replace(path, ".js", "");
        path = StringUtility.replace(path, ".cls", "");

        String className = StringUtility.replace(path, getUrlPrefix(), ".");

        if (projectName.indexOf(ProjectCacheManager.VERSIONTOKEN) > -1) {
            projectName = projectName.split(ProjectCacheManager.VERSIONTOKEN)[0];
        }

        File file = new File(JDSUtil.getJdsRealPath() + "webapp/" + projectName + "/cls/" + MD5.getHashString(className));
        log.info("className=" + className);
        log.info("file=" + file.getPath());

        RequestMethodBean requestMethodBean = getRequestMethodBean(request);


        FileInfo fileInfo = null;

        if (requestMethodBean != null) {
            path = this.formatPath(request.getUrl(), projectName);
            // 激活下载操作
            InputStream stream = null;
            try {
                path = StringUtility.replace(path, ".js", ".cls");
                if (fileInfo == null) {
                    try {
                        fileInfo = ESDFacrory.getESDClient().getFileByPath(path, projectName);
                    } catch (JDSException e) {
                        e.printStackTrace();
                    }
                }
                if (fileInfo == null) {
                    try {
                        fileInfo = ESDFacrory.getESDClient().getFileByPath(path, CustomViewFactory.DSMdsm);
                    } catch (JDSException e) {
                        e.printStackTrace();
                    }
                }
                if (fileInfo == null) {
                    fileInfo = getVfsClient().getFileByPath(path);
                }

            } catch (JDSException e) {
                e.printStackTrace();
            }
        }


        if (fileInfo != null) {
            if (!file.exists()) {
                file = new File(JDSUtil.getJdsRealPath() + resourceMount + getUrlPrefix() + projectName + "/cls/" + MD5.getHashString(className));
            }
            if (!file.exists()) {
                file = new File(JDSUtil.getJdsRealPath() + "webapp/" + "/DSMdsm/cls/" + MD5.getHashString(className));
            }

            if (!file.exists()) {
                file = new File(JDSUtil.getJdsRealPath() + resourceMount + "/DSMdsm/cls/" + MD5.getHashString(className));
            }
        }


        InputStream is = null;
        if (file != null && file.exists()) {
            is = new FileInputStream(file);
            if (mimeType == null || is == null) {
                log.warning("Resource was not found or the mime type was not understood. (Found file=" + (is != null) + ") (Found mime-type=" + (mimeType != null) + ")");
                return false;
            }
            if (is != null) {
                response.setMimeType(mimeType);
                response.sendResponse(is, Integer.valueOf(Long.toString(file.length())));
                return true;
            } else {
                return false;
            }
        } else if (requestMethodBean != null) {

            MethodConfig methodConfig = null;
            try {
                methodConfig = ESDFacrory.getESDClient().getMethodAPIBean(path, projectName);
            } catch (JDSException e) {
                e.printStackTrace();
            }
            if (methodConfig != null && methodConfig.isModule()) {
                return sendModule(className, request, response);
            } else {
                return false;
            }
        } else {
            return false;
        }

    }


    public CtVfsService getVfsClient() {
        if (vfsClient == null) {
            this.vfsClient = new CtAdminVfsServiceImpl();
        }
        return vfsClient;
    }
}
